package other;

import android.os.Handler;
import android.os.Message;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Arrays;

/**
 * @description：
 * @author： HD
 * @time：2017/8/29
 */

public class UDPServer implements Runnable {


    private int mPort;

    private Handler mHandler;
    private DatagramSocket mDatagramSocket;

    private String mLocalIP;


    /**
     * @param localIP 本机的IP地址
     * @param port
     * @param handler
     */
    public UDPServer(String localIP ,int port ,Handler handler){
        mLocalIP = localIP;
        mPort = port;
        mHandler = handler;
    }

    private void sendMessage(int what, Object obj) {
        if (mHandler != null) {
            Message.obtain(mHandler, what, obj).sendToTarget();
        }
    }


    @Override
    public void run() {

        try {

            DatagramPacket receivePacket = new DatagramPacket(new byte[1024], 1024);

            mDatagramSocket = new DatagramSocket(mPort);

            LogUtils.i("Server current start......");

            while (true) {

                mDatagramSocket.receive(receivePacket);
                byte[] recvByte = Arrays.copyOfRange(receivePacket.getData(), 0, receivePacket.getLength());

                String receiveData = new String(recvByte);

                sendMessage(0, "接收完成:" + receiveData);


                int port = receivePacket.getPort();
                InetAddress inetAddress = receivePacket.getAddress();

                byte[] ipByte = mLocalIP.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(ipByte,
                        ipByte.length, inetAddress, port);
                mDatagramSocket.send(sendPacket);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    public void close(){
        mDatagramSocket.close();
    }

}
